/*
This tutorial will briefly show how to use the terrain renderer of Irrlicht. It will also
show the terrain renderer triangle selector to be able to do collision detection with
terrain.

Note that the Terrain Renderer in Irrlicht is based on Spintz' GeoMipMapSceneNode, lots
of thanks go to him.
DeusXL provided a new elegant simple solution for building larger area on small heightmaps
-> terrain smoothing.
In the beginning there is nothing special. We include the needed header files and create
an event listener to listen if the user presses the 'W' key so we can switch to wireframe
mode and if he presses 'D' we toggle to material between solid and detail mapped.
*/
#include <irrlicht.h>
#include <iostream>

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

#pragma comment(lib, "Irrlicht.lib")

//variable to check if i shot
bool shot= false;

class MyEventReceiver : public IEventReceiver
{
public:
       bool OnEvent(SEvent event)
       {
            //check if user clicked the left mouse button
            if (event.EventType == irr::EET_MOUSE_INPUT_EVENT && !event.MouseInput.Event)
            {
             switch (event.MouseInput.Event)
             {
                      case irr::EMIE_LMOUSE_PRESSED_DOWN:
                           shot = true;
                           return true;
             }
            }
            return false;
       }
};



/*
The start of the main function starts like in most other example. We ask the user
for the desired renderer and start it up.
*/
int main()
{
	// let user select driver type


	{

	}

	//Create Irrlicht, the driver, the scene manager, and triangle selectors
   IrrlichtDevice *device =
      createDevice(EDT_OPENGL,dimension2d<s32>(1024, 768),
	32 ,true, false, 0);

    SKeyMap keyMap[9];
   keyMap[0].Action = EKA_MOVE_FORWARD;
   keyMap[0].KeyCode = KEY_UP;
   keyMap[1].Action = EKA_MOVE_FORWARD;
   keyMap[1].KeyCode = KEY_KEY_W;

   keyMap[2].Action = EKA_MOVE_BACKWARD;
   keyMap[2].KeyCode = KEY_DOWN;
   keyMap[3].Action = EKA_MOVE_BACKWARD;
   keyMap[3].KeyCode = KEY_KEY_S;

   keyMap[4].Action = EKA_STRAFE_LEFT;
   keyMap[4].KeyCode = KEY_LEFT;
   keyMap[5].Action = EKA_STRAFE_LEFT;
   keyMap[5].KeyCode = KEY_KEY_A;

   keyMap[6].Action = EKA_STRAFE_RIGHT;
   keyMap[6].KeyCode = KEY_RIGHT;
   keyMap[7].Action = EKA_STRAFE_RIGHT;
   keyMap[7].KeyCode = KEY_KEY_D;



	/*
	First, we add standard stuff to the scene: A nice irrlicht engine
	logo, a small help text, a user controlled camera, and we disable
	the mouse cursor.
	*/


	video::IVideoDriver* driver = device->getVideoDriver();
	scene::ISceneManager* smgr = device->getSceneManager();
	gui::IGUIEnvironment* env = device->getGUIEnvironment();
    //scene::IMetaTriangleSelector* metaSelector;
    //scene::ISceneNodeAnimatorCollisionResponse* anim1;


	driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);

    // add camera
	scene::ICameraSceneNode* camera =
		smgr->addCameraSceneNodeFPS(0,120.0f,400.0f,-1,keyMap,9,true, 1.5f);
	camera->setPosition(core::vector3df(1000,1000,1000));
	camera->setTarget(core::vector3df(600,800,10000));
	camera->setFarValue(12000.0f);

    // disable mouse cursor
	device->getCursorControl()->setVisible(false);

    /*
	Here comes the terrain renderer scene node: We add it just like any
	other scene node to the scene using ISceneManager::addTerrainSceneNode().
	The only parameter we use is a file name to the heightmap we use. A heightmap
	is simply a gray scale texture. The terrain renderer loads it and creates
	the 3D terrain from it.
	To make the terrain look more big, we change the scale factor of it to (40, 4.4, 40).
	Because we don't have any dynamic lights in the scene, we switch off the lighting,
	and we set the file terrain-texture.jpg as texture for the terrain and
	detailmap3.jpg as second texture, called detail map. At last, we set
	the scale values for the texture: The first texture will be repeated only one time over
	the whole terrain, and the second one (detail map) 20 times.
	*/

	// add terrain scene node
	scene::ITerrainSceneNode* terrain = smgr->addTerrainSceneNode(
		"../../media/terrain-heightmap.bmp",
		0,										// parent node
		-1,										// node id
		core::vector3df(0.f, 0.f, 0.f),			// position
		core::vector3df(0.f, 0.f, 0.f),			// rotation
		core::vector3df(40.f, 4.4f, 40.f),		// scale
		video::SColor ( 255, 255, 255, 255 ),	// vertexColor,
		5,										// maxLOD
		scene::ETPS_17,							// patchSize
		1										// smoothFactor
		);

	terrain->setMaterialFlag(video::EMF_LIGHTING, false);
    terrain->setMaterialTexture(1, driver->getTexture("../../media/ground.jpg"));
    terrain->setMaterialTexture(0, driver->getTexture("../../media/terraintexture.jpg"));
	terrain->setMaterialFlag(video::EMF_FOG_ENABLE, true);
	terrain->setMaterialType(video::EMT_DETAIL_MAP);

	terrain->scaleTexture(1.0f, 20.0f);
	//terrain->setDebugDataVisible ( true );

    // create triangle selector for the terrain
	scene::ITriangleSelector* selector
		= smgr->createTerrainTriangleSelector(terrain, 0);
    terrain->setTriangleSelector(selector);
    scene::IMetaTriangleSelector* metaSelector
        = smgr->createMetaTriangleSelector();
	// create collision response animator and attach it to the camera
    scene::ISceneNodeAnimator* anim =
	anim = smgr->createCollisionResponseAnimator(
		 selector, camera, core::vector3df(60,80,60),
		core::vector3df(0,-10.0f,0),
		core::vector3df(0,50,0));
	selector->drop();
	camera->addAnimator(anim);
	anim->drop();
	metaSelector->drop();

    //fog :)
	driver->setFog(video::SColor(0,230,230,230), true, 500, 10000, 500, true);

    //model loading
    scene::IAnimatedMesh* mesh = smgr->getMesh("../../media/8462kgun.3ds");
        scene::IAnimatedMesh* mesh1 = smgr->getMesh("../../media/speeder.3ds");
            scene::IAnimatedMesh* mesh2 = smgr->getMesh("../../media/tank.3ds");

	scene::ISceneNode* node = 0;

	node = smgr->addAnimatedMeshSceneNode(mesh);
    node->setParent(camera);
    node->getPosition(); //relative position
    node->getAbsolutePosition(); //world coordinates
    node->setMaterialTexture(1,	driver->getTexture("../../media/scope.jpg"));
    node->getMaterial(1).SpecularColor.set(0,0,0,0);
    node->setPosition(core::vector3df(20,-30,30));

    //model two

    //node = smgr->addAnimatedMeshSceneNode(mesh1);
	//if (mesh1)
	//{
		//scene::ISceneNodeAnimator* anim =
			//smgr->createFlyStraightAnimator(core::vector3df(6000,2000,30000),
			//core::vector3df(6000,2000,-10000), 2000, true);
		//node->addAnimator(anim);
		//anim->drop();
	//}
	//node->setMaterialTexture(0,	driver->getTexture("../../media/wall.bmp"));
	//node->getMaterial(0).SpecularColor.set(0,0,0,0);

    //model 3

    node = smgr->addAnimatedMeshSceneNode(mesh2);
    if (mesh2)
    {
    node->getMaterial(0).SpecularColor.set(0,0,0,0);
    node->setPosition(core::vector3df(4500,600,5000));
	node->setMaterialTexture(0,	driver->getTexture("../../media/wall.bmp"));
	node->getMaterial(0).SpecularColor.set(0,0,0,0);
    //selector = smgr->createTriangleSelector();
    //metaSelector->addTriangleSelector(selector);
    //selector->drop();
    }
	// add animated water

	mesh = smgr->addHillPlaneMesh("myHill",
		core::dimension2d<f32>(40,60),
		core::dimension2d<u32>(40,40), 0, 0,
		core::dimension2d<f32>(0,0),
		core::dimension2d<f32>(10,10));

	node = smgr->addWaterSurfaceSceneNode(mesh->getMesh(0), 3.0f, 300.0f, 30.0f);
	node->setPosition(core::vector3df(1300,200,2700));

    node->setMaterialTexture(0, driver->getTexture("../../media/stones.jpg"));
	node->setMaterialTexture(1, driver->getTexture("../../media/water1.jpg"));

	node->setMaterialType(video::EMT_REFLECTION_2_LAYER);

	core::vector3df waypoint[2];
	waypoint[0].set(-150,40,100);
	waypoint[1].set(350,40,100);

    //light
    scene::ILightSceneNode* light1 =
		smgr->addLightSceneNode(0, core::vector3df(0,10000,0),
		video::SColorf(1.0f,1.0f,1.0f,1.0f),
		600.0f);
		// attach billboard to the light
	scene::ISceneNode* bill =
		smgr->addBillboardSceneNode(light1, core::dimension2d<f32>(1000, 1000));

	bill->setMaterialFlag(video::EMF_LIGHTING, false);
	bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
	bill->setMaterialTexture(0, driver->getTexture("../../media/particlewhite.bmp"));
	/*
	To be able to do collision with the terrain, we create a triangle selector.
	If you want to know what triangle selectors do, just take a look into the
	collision tutorial. The terrain triangle selector works together with the
	terrain. To demonstrate this, we create a collision response animator
	and attach it to the camera, so that the camera will not be able to fly
	through the terrain.
	*/
    // create a particle system

	scene::IParticleSystemSceneNode* ps = 0;
	ps = smgr->addParticleSystemSceneNode(false);
	ps->setPosition(core::vector3df(4500,600,5000));
	ps->setScale(core::vector3df(20,20,20));

	ps->setParticleSize(core::dimension2d<f32>(250.0f, 250.0f));

	scene::IParticleEmitter* em = ps->createBoxEmitter(
		core::aabbox3d<f32>(-7,0,-7,7,1,7),
		core::vector3df(0.6f,1.06f,0.4f),
		80,100,
		video::SColor(0,255,255,255), video::SColor(0,255,255,255),
		800,2000);

	ps->setEmitter(em);
	em->drop();

	scene::IParticleAffector* paf =
		ps->createFadeOutParticleAffector();

	ps->addAffector(paf);
	paf->drop();

    ps->setMaterialFlag(video::EMF_LIGHTING, false);
	ps->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	ps->setMaterialTexture(0, driver->getTexture("../../media/smoke.bmp"));
	ps->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);

    // create skybox
	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);

	smgr->addSkyBoxSceneNode(
		driver->getTexture("../../media/background.bmp"),
		driver->getTexture("../../media/background.bmp"),
		driver->getTexture("../../media/background.bmp"),
		driver->getTexture("../../media/background.bmp"),
		driver->getTexture("../../media/background.bmp"),
		driver->getTexture("../../media/background.bmp"));

	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true);



	/*
	That's it, draw everything. Now you know how to use terrain in Irrlicht.
	*/

	int lastFPS = -1;

	while(device->run())
	if (device->isWindowActive())
	{
		driver->beginScene(true, true, 0 );

		smgr->drawAll();
		env->drawAll();

		driver->endScene();
        // display frames per second in window title
		int fps = driver->getFPS();
		if (lastFPS != fps);


	}

	device->drop();

	return 0;
}
